package net.chengp.ms.auth.controller;

import java.security.Principal;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;
import net.chengp.ms.commons.result.R;
import net.chengp.ms.commons.result.Result;

@RestController
@RequestMapping("/oauth")
@Slf4j
public class OauthController {

	@Autowired
	private TokenEndpoint tokenEndpoint;
	@Autowired
	private CheckTokenEndpoint checkTokenEndpoint;

	@GetMapping("/token")
	public Result<DefaultOAuth2AccessToken> getAccessToken(Principal principal,
			@RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
		return custom(principal, parameters);
	}

	@PostMapping("/token")
	public Result<DefaultOAuth2AccessToken> postAccessToken(Principal principal,
			@RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
		return custom(principal, parameters);
	}

	@RequestMapping("/check_token")
	public Result<Map<String, ?>> check_token(@RequestParam("token") String value) {
		try {
			return R.ok(checkTokenEndpoint.checkToken(value));
		} catch (Exception e) {
			log.error("校验token失败!", e);
			return R.error(e);
		}
	}

	private Result<DefaultOAuth2AccessToken> custom(Principal principal, Map<String, String> parameters) {
		try {
			OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
			DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
			return R.ok(token);
		} catch (Exception e) {
			log.error("获取token失败!", e);
			return R.error(e);
		}
	}

}